/*****************************************************************
 *Yuga Technology
 *@author Oplink OMS
 *@copyright all rights reserved (c) zengkang007@gmail.com
 *****************************************************************/
package com.oplink.webbase.modules.core.web;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.oplink.webbase.modules.cfg.entity.CfgCard;
import com.oplink.webbase.modules.cfg.entity.CfgSlot;
import com.oplink.webbase.modules.cfg.services.CfgCardService;
import com.oplink.webbase.modules.cfg.services.CfgNeService;
import com.oplink.webbase.modules.cfg.services.CfgSiteService;
import com.oplink.webbase.modules.cfg.services.CfgSlotService;
import com.oplink.webbase.modules.core.entity.Index;
import com.oplink.webbase.modules.core.service.IndexService;
import com.oplink.webbase.modules.sys.entity.Config;
import com.oplink.webbase.modules.sys.entity.Menu;
import com.oplink.webbase.modules.sys.entity.User;
import com.oplink.webbase.modules.sys.service.ConfigService;
import com.oplink.webbase.modules.sys.service.MenuService;
import com.oplink.webbase.modules.sys.service.ShiroDbRealm.ShiroUser;
import com.oplink.webbase.modules.sys.utils.ModuleUtils;
import com.oplink.webbase.modules.sys.web.BaseController;

/**
 * Index管理的Controller, 使用Restful风格的Urls: List page : GET /queue/ Create pushlet
 * : GET /queue/pushlet Create page : GET /queue/create Create action : POST
 * /queue/create Update page : GET /queue/update/{id} Update action : POST
 * /queue/update Delete action : GET /queue/delete/{id} 告警Controller
 * 
 * @author Oplink OMS
 * @version 2014-08-11
 */
@Controller
@RequestMapping(value = "core/index")
public class IndexController extends BaseController {

	// @Autowired
	// private AlarmHistService alarmHistService;

	@Autowired
	private CfgSiteService cfgSiteService;

	/*
	 * @Autowired
	 * private AlarmCurrentService acurrentservice;
	 */

	@Autowired
	private IndexService indexService;

	@Autowired
	private MenuService menuService;

	// @Autowired
	// private SnmpService snmpService;

	@Autowired
	private ConfigService cfgService;

	@Autowired
	private CfgNeService neService;

	@Autowired
	private CfgSlotService slotService;

	@Autowired
	private CfgCardService cardService;

	@RequiresPermissions("modules/core:index:view")
	@RequestMapping(value = { "list", "" }, method = { RequestMethod.GET, RequestMethod.POST })
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		// // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), null);
		// SccCard cardTemp = new SccCard(1, 5);
		// // List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		// String cnt = "";
		// try {
		// String alarm = snmpService.get(cardTemp, "GetCurrentAlarm");
		// System.out.println("alarm <>>>>>> " + alarm);
		// if (alarm != null) {
		// String[] aArr = alarm.split(",");
		// String[] barr = null;
		// cnt = aArr[0].replace("AlarmCnt=", "").trim();
		// String slotStr = "", alarmname = "", splitTemp = "", otime = "";
		// Map<String, String> map = new HashMap<String, String>();
		// for (int i = 1; i < aArr.length; i++) {
		// map = new HashMap<String, String>();
		// barr = aArr[i].split(":");
		// slotStr = barr[0];
		// alarmname = barr[1];
		// splitTemp = slotStr + ":" + alarmname + ":";
		// otime = aArr[i].replace(splitTemp, "").trim();
		// map.put("slot", slotStr.replace("Slot", "").trim().concat("号"));
		// map.put("aname", alarmname);
		// map.put("otime", otime);
		// list.add(map);
		// }
		// }
		// List<AlarmCurrent> alist = acurrentservice.getCurrentAlarm();
		List<Menu> listMenu = menuService.findAll();
		String path = request.getContextPath();
		String domMenu = menuService.generateMenuDom(listMenu, path);
		model.addAttribute("domMenu", domMenu);
		// model.addAttribute("alist", alist);
		// model.addAttribute("acnt", cnt);
		//
		// List<CfgSite> siteList = cfgSiteService.getAllSite();
		// TreeMap<Integer, Integer> allCount = AlarmUtils.getAllAlarmCount(siteList);
		// model.addAttribute("allCount1", allCount.get(1) == null ? 0 : allCount.get(1));
		// model.addAttribute("allCount2", allCount.get(2) == null ? 0 : allCount.get(2));
		// model.addAttribute("allCount3", allCount.get(3) == null ? 0 : allCount.get(3));
		// model.addAttribute("allCount4", allCount.get(4) == null ? 0 : allCount.get(4));
		// model.addAttribute("allCount0", allCount.get(-1) == null ? 0 : allCount.get(-1));
		//
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// model.addAttribute("pages", pages);
		return "modules/sys/ace/sysIndex";
	}

	@RequiresPermissions("modules/core:index:edit")
	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	@ResponseBody
	public Index updateForm(@PathVariable("id") Long id) {
		Index index = indexService.getIndex(id);
		index.setUser(null);
		return index;
	}

	/**
	 * 根据目录查找配置列表
	 * 
	 * @param catalog
	 * @return
	 */
	@RequiresPermissions("modules/core:index:edit")
	@RequestMapping(value = "findCfgByCatalog/{catalog}", method = RequestMethod.GET)
	@ResponseBody
	public List<Config> findCfgByCatalog(@PathVariable("catalog") String catalog) {
		return ModuleUtils.getModuleList(catalog);
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute("index") Index index, RedirectAttributes redirectAttributes) {
		try {
			User user = new User(getCurrentUserId());
			index.setUser(user);
			indexService.saveIndex(index);
			redirectAttributes.addFlashAttribute("message", "更新任务成功");
			return "1";
		} catch (Exception e) {
			return "0";
		}
	}

	@RequiresPermissions("modules/core:index:view")
	@RequestMapping(value = "form")
	public String form(Index index, Model model) {
		model.addAttribute("index", index);
		return "modules/core/indexForm";
	}

	@RequestMapping(value = "topo")
	public String topo() {
		return "modules/core/topo/index";
	}

	@RequestMapping(value = "subTopo")
	public String subTopo() {
		return "modules/core/topo/subTopo";
	}

	@RequestMapping(value = "userLog")
	public String userLog() {
		return "modules/core/log/userLog";
	}

	@RequestMapping(value = "commLog")
	public String commLog() {
		return "modules/core/log/commLog";
	}

	@RequestMapping(value = "upload")
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1024 * 1024 * 20);
		factory.setRepository(new File(request.getRealPath("/")));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(1024 * 1024 * 20);

		try {
			DiskFileItem item = (DiskFileItem) (upload.parseRequest(request).get(0));

			// save file
			String filename = item.getName();
			int index = filename.lastIndexOf("//");
			filename = filename.substring(index + 1, filename.length());
			long fileSize = item.getSize();

			if (filename.equals("") && (fileSize == 0)) {
				return;
			}

			File uploadedFile = new File("d:" + File.separator + filename);
			item.write(uploadedFile);
			PrintWriter outNet = response.getWriter();
			outNet.println("{\"files\":[{\"name\":\"" + "ok" + "\"}]}");
			outNet.flush();
			outNet.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequiresPermissions("modules/core:index:edit")
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		model.addAttribute("userId", getCurrentUserId());
		model.addAttribute("action", "create");
		return "modules/core/index/create";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public String create(Index index, RedirectAttributes redirectAttributes, Model model) {
		try {
			User user = new User(getCurrentUserId());
			index.setUser(user);
			model.addAttribute("index", index);
			indexService.saveIndex(index);
			redirectAttributes.addFlashAttribute("message", "创建任务成功");
			return "1";
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	@RequestMapping(value = "delete/{id}")
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			String ret = "0";
			if (!"".equals(id)) {
				String[] delList = id.split(",");
				for (String idItem : delList) {
					indexService.deleteIndex(Long.valueOf(idItem));
				}
				redirectAttributes.addFlashAttribute("message", "删除任务成功");
				ret = "1";
			} else {
				ret = "0";
			}
			return ret;
		} catch (Exception e) {
			return "0";
		}
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}

	// ---------------------------- 性能管理（开始）-----------------------------------------
	/**
	 * 当前性能同步
	 */
	/*
	 * @RequestMapping(value = "currentsync", method = { RequestMethod.GET, RequestMethod.POST })
	 * public String currentsync(AlarmHistory alarmHist, HttpServletRequest request, HttpServletResponse response,
	 * Model model) {
	 * // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), alarmHist);
	 * // model.addAttribute("pages", pages);
	 * return "modules/core/perf/currentPerfSync";
	 * }
	 */

	/**
	 * 实时性能同步
	 */
	@RequestMapping(value = "realtimesync")
	public String realtimesync() {
		return "modules/core/perf/realtimeSync";
	}

	/**
	 * 历史性能查询
	 */
	// @RequestMapping(value = "histperfquery", method = { RequestMethod.GET, RequestMethod.POST })
	// public String histperfquery(AlarmHistory alarmHist, HttpServletRequest request, HttpServletResponse response,
	// Model model) {
	// // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), alarmHist);
	// // model.addAttribute("pages", pages);
	// return "modules/core/perf/histperfQuery";
	// }

	// ---------------------------- 性能管理（结束）-----------------------------------------

	// ---------------------------- 故障管理（开始）-----------------------------------------
	/**
	 * 告警属性查询
	 */
	/*
	 * @RequestMapping(value = "alarmproquery", method = { RequestMethod.GET, RequestMethod.POST })
	 * public String alarmProQuery(AlarmHistory alarmHist, HttpServletRequest request, HttpServletResponse response,
	 * Model model) {
	 * // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), alarmHist);
	 * // model.addAttribute("pages", pages);
	 * return "modules/core/alarm/alarmproquery";
	 * }
	 *//**
	 * 告警属性修改
	 */
	/*
	 * @RequestMapping(value = "alarmproupdate", method = { RequestMethod.GET, RequestMethod.POST })
	 * public String alarmProUpdate(AlarmHistory alarmHist, HttpServletRequest request, HttpServletResponse response,
	 * Model model) {
	 * // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), alarmHist);
	 * // model.addAttribute("pages", pages);
	 * return "modules/core/alarm/alarmproupdate";
	 * }
	 */

	/**
	 * 历史告警查询(含统计)
	 */
	/*
	 * @RequestMapping(value = "histalarmquery", method = { RequestMethod.GET, RequestMethod.POST })
	 * public String histalarmquery(AlarmHistory alarmHist, HttpServletRequest request, HttpServletResponse response,
	 * Model model) {
	 * // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), alarmHist);
	 * // model.addAttribute("pages", pages);
	 * return "modules/core/alarm/histalarmquery";
	 * }
	 *//**
	 * 当前告警同步(含统计)
	 */
	/*
	 * @RequestMapping(value = "currentalarmsync")
	 * public String histalarmsync(AlarmHistory alarmHist, HttpServletRequest request, HttpServletResponse response,
	 * Model model) {
	 * // Page<AlarmHist> pages = alarmHistService.find(new Page<AlarmHist>(request, response), alarmHist);
	 * // model.addAttribute("pages", pages);
	 * return "modules/core/alarm/currentalarmsync";
	 * }
	 */
	// ---------------------------- 故障管理（结束）-----------------------------------------

	// ------------------------------配置管理 Start ------------------------------------------//
	/**
	 * 网元视图
	 */
	@RequestMapping(value = "neChassis")
	public String neChassis(HttpServletRequest request, Model model) {
		/*
		 * List<Map<String, String>> listOut = cfgService.findCfgValue(UserUtils.getCurrentUserId(), "mgr_card");
		 * model.addAttribute("list", listOut);
		 */
		String nid = request.getParameter("nid");
		nid = nid.substring(nid.indexOf("_") + 1);
		List<CfgSlot> slotList = neService.getSlotByNid(Long.parseLong(nid));
		model.addAttribute("list", slotList);
		return "modules/core/configmgr/neChassisIndex";
	}

	/**
	 * 板卡配置
	 * id 可能是通过tree点击过来 'x_x_x'组合方式，或者是机架视图点击过来的 xx 格式。
	 * 
	 * @return
	 */
	@RequestMapping(value = "cardConfig/{id}")
	public String cardConfig(@PathVariable("id") String id, Model model) {
		Long cid = 0L;
		if (id.indexOf("_") > 0) {
			String nid = id.substring(id.indexOf("_") + 1, id.lastIndexOf("_"));
			id = id.substring(id.lastIndexOf("_") + 1);
			if ((nid != null) && !nid.equals("") && (id != null) && !id.equals("")) {
				cid = slotService.getcard(Long.parseLong(nid), Long.parseLong(id));
			}
		} else {
			cid = Long.parseLong(id);
		}

		// 返回板卡类型
		CfgCard card = cardService.getCfgCard(cid);
		if (card != null) {
			model.addAttribute("cardType", card.getType());
		}
		model.addAttribute("cid", cid);
		return "modules/core/configmgr/cardConfig";
	}

	// ------------------------------配置管理 End --------------------------------------------//
	@RequestMapping(value = "test")
	@ResponseBody
	public String testTriggerMessage() {
		/*
		 * BaseEvent be = new BaseEvent();
		 * be.setAction(BaseEvent.ACTION_VALUE_OFF);
		 * be.setType(BaseEvent.TYPE_ALARM_NE);
		 * AlarmCurrent ac = neService.getAllNe().get(0).getAcurlist().get(0);
		 * be.setEntity(ac);
		 * ec.put(be);
		 */

		return "1";
	}
}
